package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.DBConnector;
import cmput391.src.queries.SecurityQueries;
import cmput391.src.queries.UserManagementQueries;
import entities.User;

/**
 * Servlet implementation class EditUser
 */
@WebServlet("/EditUser")
public class EditUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);
		
		//Prepare the current date (could do this just using Oracle commands, but this way it works with MySQL as well)
		java.util.Date currentDatetime = new java.util.Date(System.currentTimeMillis());  
		java.sql.Timestamp timestamp = new java.sql.Timestamp(currentDatetime.getTime());
		
		//Get all the POSTed variables
		User user = new User(
				(request.getParameter("username")).trim(), 
				(request.getParameter("password")).trim(), 
				(request.getParameter("userclass")),
				timestamp, 
				(request.getParameter("first_name")).trim(), 
				(request.getParameter("last_name")).trim(),
				(request.getParameter("address")).trim(), 
				(request.getParameter("email")).trim(), 
				(request.getParameter("phone")).trim()
			);

		/* Data Validation */
		
		//Check username isn't blank
		if ((user.getUserName()).trim().equals("")) {
			messages.put("update_msg", "<span class=\"message validation\">Username is required..</span>");
		}
		
		//Check password isn't blank
		if ((user.getPassword()).trim().equals("")) {
			messages.put("update_msg", "<span class=\"message validation\">Password is required..</span>");
		}
		
		//Check email isn't blank
		if ((user.getEmail()).trim().equals("")) {
			messages.put("update_msg", "<span class=\"message validation\">Email is required..</span>");
		}		
		
		if (messages.size() > 0) {
			request.getRequestDispatcher("admin.jsp").forward(request, response);	
			return;				
		}
		
		
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries uq = new UserManagementQueries(dbConnect.getConnection(), security);
			
			uq.updateFirstName(user.getUserName(), user.getFirstName());
			uq.updateLastName(user.getUserName(), user.getLastName());
			uq.updatePassword(user.getUserName(), user.getPassword());
			uq.updateUserClass(user.getUserName(), user.getUserClass());
			uq.updateAddress(user.getUserName(), user.getAddress());
			uq.updateEmail(user.getUserName(), user.getEmail());
			uq.updatePhone(user.getUserName(), user.getPhone());
			
			messages.put("update_msg", "<span class=\"message success\">User Info for "+user.getUserName()+" updated.</span>");

			request.getRequestDispatcher("EditForm?user_name="+user.getUserName()).include(request,response);
			
			
		} catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
			messages.put("update_msg", "<span class=\"message error\">This email address is already in use. Try another one.</span>");
			request.getRequestDispatcher("EditForm?user_name="+user.getUserName()).include(request,response);
			e.printStackTrace();			
		} catch (SQLException e) {
			messages.put("update_msg", "<span class=\"message error\">User could not be updated. Please try again.</span>");
			request.getRequestDispatcher("EditForm?user_name="+user.getUserName()).include(request,response);
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}

}
